﻿using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Read.Application.Command.PackagingPlanCommands;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Read.Application.CommandHander.PackagingPlanCommandHandlers
{
    public class GetPackagingPlanCommandHandler : IRequestHandler<GetPackagingPlanCommands, APIResult<APIPaging<PackagingPlan>>>
    {
        private readonly ISqlSugarClient db;

        public GetPackagingPlanCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<PackagingPlan>>> Handle(GetPackagingPlanCommands request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<PackagingPlan>> result = new APIResult<APIPaging<PackagingPlan>>();
            result.code = APIResultCode.success;
            result.msg = "查询显示成功";

            var list = db.Queryable<PackagingPlan>();

            if (request.ScheduledDates != null)
            {
                list = list.Where(p => p.ScheduledDates == request.ScheduledDates);
            }
            if (!string.IsNullOrEmpty(request.ProductionUnits))
            {
                list = list.Where(p => p.ProductionUnits == request.ProductionUnits);
            }
            if (request.isload != null)
            {
                list = list.Where(p => p.isload == request.isload);
            }

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.PackagingPlanId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<PackagingPlan> paging = new APIPaging<PackagingPlan>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
